Find Median from Data Stream

Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.

Examples:

[2,3,4] , the median is 3

[2,3], the median is (2 + 3) / 2 = 2.5

Design a data structure that supports the following two operations:

  • void addNum(int num) - Add a integer number from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

For example:

  1. add(1)
  2. add(2)
  3. findMedian() -> 1.5
  4. add(3)
  5. findMedian() -> 2

Solution:

  1. class MedianFinder {
  2. // Max heap
  3. PriorityQueue<Integer> left = new PriorityQueue<>(new Comparator<Integer>() {
  4. public int compare(Integer a, Integer b) { return b - a; }
  5. });
  6. // Min heap
  7. PriorityQueue<Integer> right = new PriorityQueue<>(new Comparator<Integer>() {
  8. public int compare(Integer a, Integer b) { return a - b; }
  9. });
  10. // Adds a number into the data structure.
  11. public void addNum(int num) {
  12. double m = findMedian();
  13. int diff = left.size() - right.size();
  14. // left and right are balanced
  15. if (diff == 0) {
  16. if (num < m) {
  17. left.offer(num);
  18. } else {
  19. right.offer(num);
  20. }
  21. }
  22. // left has more elements than right
  23. else if (diff > 0) {
  24. if (num < m) {
  25. if (left.size() > 0) right.offer(left.poll());
  26. left.offer(num);
  27. } else {
  28. right.offer(num);
  29. }
  30. }
  31. // right has more elements than left
  32. else {
  33. if (num < m) {
  34. left.offer(num);
  35. } else {
  36. if (right.size() > 0) left.offer(right.poll());
  37. right.offer(num);
  38. }
  39. }
  40. }
  41. // Returns the median of current data stream
  42. public double findMedian() {
  43. if (left.size() == 0 && right.size() == 0) {
  44. return 0.0;
  45. }
  46. int diff = left.size() - right.size();
  47. // left and right are balanced
  48. if (diff == 0) {
  49. return (left.peek() + right.peek()) / 2.0;
  50. }
  51. // left has more elements than right
  52. else if (diff > 0) {
  53. return left.peek();
  54. }
  55. // right has more elements than left
  56. else {
  57. return right.peek();
  58. }
  59. }
  60. };
  61. // Your MedianFinder object will be instantiated and called as such:
  62. // MedianFinder mf = new MedianFinder();
  63. // mf.addNum(1);
  64. // mf.findMedian();